<template>
  <div class="bc-query-panel">
    <div v-for="(item, index) in queries" :key="index" class="bc-query-item">
      <div class="query-item-control">
        <!-- 选择器 -->
        <bc-query-select
          v-model="queryForm[item.prop]"
          :config="item"
          :form="queryForm"
          v-if="item.type === 'select'"
        />
        <!-- 时间范围选择器 -->
        <bc-query-date-picker
          v-model="queryForm[item.prop]"
          :config="item"
          v-else-if="['date', 'month', 'datetime'].includes(item.type)"
        />
        <!-- 数组 -->
        <bc-query-number v-model="queryForm[item.prop]" :config="item" v-else-if="item.type === 'number'" />
        <!-- 范围 -->
        <bc-query-input-range v-model="queryForm[item.prop]" :config="item" v-else-if="item.type === 'range'" />
        <!-- 文本 -->
        <bc-query-input v-model="queryForm[item.prop]" :config="item" v-else />
      </div>
    </div>
  </div>
</template>

<script setup>
import BcQueryInput from './components/BcQueryInput.vue'
import BcQueryNumber from './components/BcQueryNumber.vue'
import BcQuerySelect from './components/BcQuerySelect.vue'
import BcQueryDatePicker from './components/BcQueryDatePicker.vue'
import BcQueryInputRange from './components/BcQueryInputRange.vue'
/**
 * queryOptions配置项
 * type: select|date|month|datetime|number
 * prop: form key
 * label: 字段名
 * startProp: date|month|datetime|range 专用，起始值key
 * endProp: date|month|datetime|range 专用，结束值key
 * format: date|month专用，时间展示格式
 * options: select专用，枚举项[{value:"",label:""}]
 * bindProps: 原始属性
 */
const emits = defineEmits(['query', 'reset'])
const props = defineProps({
  // 查询项
  queries: {
    type: Array,
    default: () => [],
  },
})

// 查询
const queryForm = reactive({})
const handleQuery = () => {
  const params = { ...queryForm }
  props.queries
    .filter((i) => ['date', 'month', 'datetime', 'range'].includes(i.type))
    .map((i) => {
      if (params[i.prop] && i.startProp && i.endProp) {
        params[i.startProp] = params[i.prop][0]
        params[i.endProp] = params[i.prop][1]
        delete params[i.prop]
      }
    })
  emits('query', params)
}
watch(
  queryForm,
  () => {
    handleQuery()
  },
  { deep: true }
)
</script>

<style lang="scss" scoped>
.bc-query-panel {
  display: flex;
  gap: 12px;
  .bc-query-item {
    width: calc(50% - 6px);
    .query-item-label {
      margin-bottom: 8px;
      line-height: 20px;
      white-space: nowrap;
      font-size: 14px;
    }
  }
}
</style>
